import 'dart:convert';

import 'package:date_util/date_util.dart';
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginAgeAndSexPage extends StatefulWidget {
  @override
  _LoginAgeAndSexPageState createState() => _LoginAgeAndSexPageState();
}

class _LoginAgeAndSexPageState extends State<LoginAgeAndSexPage> {

  bool isboy = true;
  final TextEditingController _birthControlelr = TextEditingController();
  final FocusNode _birthFocus = FocusNode();
  final GlobalKey _scaffoldKey = GlobalKey<ScaffoldState>();
  String _year = "";
  String _mouth = "";
  String _day = "";

  @override
  void dispose() {
    _birthControlelr.dispose();
    super.dispose();
  }

  _requestModify() {
    if(_birthControlelr.text.length != 8) {
      AlertTool.showToast("请填写您的生日");
      return;
    }
    Networktool.request(API.edit,params: {"gender":isboy ? 1 : 2, "birthday":"$_year-$_mouth-$_day"}, success: (data) async {
      print(data);
      if(data["data"] != null) {
        SharedPreferences share = await SharedPreferences.getInstance();
        String tempJS = json.encode(data["data"]);
        share.setString(KEY_userjosn_info, tempJS);
        Navigator.of(_scaffoldKey.currentContext).pushNamed("/username"); 
      }
    }, fail: (msg){
      AlertTool.showToast(msg);
    });
  }

  // 创建男女按钮
  Widget _createSexbutton(String text, bool isselect, Function callback) {
    return GestureDetector(
              child: Container(
                padding: const EdgeInsets.only(bottom: 35),
                child: Text(text, style: instanceTextStyle(
                  14,
                  isselect ? APP_main_color : const Color(0xff666666),
                  fontWeight: isselect ? FontWeight.w600 : FontWeight.normal
                )),
              ),
              onTap: callback,
            );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      key: _scaffoldKey,
      body: SafeArea(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () => _birthFocus.unfocus(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              IconButton(
                icon: Image.asset("assets/zhuce-fanhui.png"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              Container(
                padding: const EdgeInsets.only(top: 87, bottom: 34,left: 40),
                child: Text("年龄&性别", style: instanceTextStyle(
                  22,
                  Colors.black,
                  fontWeight: FontWeight.bold
                ),),
              ),
              Padding(
                padding: const EdgeInsets.only(left:40),
                child: Text(
                  "注册完成后，您的性别将无法更改。",
                  style: instanceTextStyle(11, APP_font_grey),
                ),
              ),
              Container(
                alignment: Alignment.center,
                margin: const EdgeInsets.only(top: 24),
                child: Container(color: Colors.blue,width: 100,height: 100),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _createSexbutton("boy", isboy, (){
                    setState(() {
                      isboy = true;
                    });
                  }),
                  _createSexbutton("girl", isboy == false, (){
                    setState(() {
                      isboy = false;
                    });
                  }),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(left: 40),
                child: Text(
                  "输入你的生日",
                  style: instanceTextStyle(11, APP_font_grey),
                ),
              ),
              Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(top: 33.5,left: 80, right: 80),
                child: Stack(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Text(_year, style: TextStyle(color: APP_main_color,fontSize: 13)),
                        Text("年", style: TextStyle(color: APP_font_black, fontSize: 11)),
                        Text(_mouth, style: TextStyle(color: APP_main_color,fontSize: 13)),
                        Text("月", style: TextStyle(color: APP_font_black, fontSize: 11)),
                        Text(_day, style: TextStyle(color: APP_main_color,fontSize: 13)),
                        Text("日", style: TextStyle(color: APP_font_black, fontSize: 11))
                      ],
                    ),
                    Container(
                      // color: Colors.blue,
                      child: TextField(
                        controller: _birthControlelr,
                        showCursor: false,
                        maxLength: 8,
                        focusNode: _birthFocus,
                        style: TextStyle(color: Colors.transparent),
                        keyboardType: TextInputType.number,
                        inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          counterText: "",
                        ),
                        onChanged: (str){
                          if(str.length <= 4) {
                            String y = str;
                            if(str == "0000") y = "1990";
                            setState(() {
                              _year = y;
                              _mouth = "";
                            });
                          } else if(str.length <= 6) {
                            String m = str.substring(4);
                            if(int.parse(m) > 12) m = "12";
                            if(m == "00") m = "01";
                            setState(() {
                              _mouth = m;
                              _day = "";
                            });
                          } else {
                            var dateUtility = DateUtil();
                            int days = dateUtility.daysInMonth(int.parse(_mouth), int.parse(_year));
                            String d = str.substring(6);
                            if(int.parse(d) > days) d = "${days}";
                            if(d == "00") d = "01";
                            setState(() {
                              _day = d;
                            });
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Spacer(),
              Center(
                child: FlatButton(
                  onPressed: _requestModify,
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 30),
                    child: Column(
                      children: [
                        Image.asset("assets/zhuce-xia.png"),
                        SizedBox(height: 20,),
                        Text("下一步", style: TextStyle(fontSize: 14, color: APP_font_black),)
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}